import React, { useEffect, useState } from "react";
import Select from "../../../Select";
import { isPromise, isUndefined } from "@ct0/functions";
import type { FieldBaseType } from "../../type";
import type { SelectOptions } from "../../../Select/type";

export default function SelectField({
  field,
  isValid,
  onChange,
}: {
  field: FieldBaseType<string | number>;
  isValid: boolean;
  onChange: (v: string | number) => void;
}) {
  const {
    value: propsValue,
    defaultValue,
    placeholder,
    options,
    disabled,
    meta,
  } = field;
  const search = meta?.search ? true : false;

  const [opts, setOpts] = useState<SelectOptions>([]);

  useEffect(() => updateOpts(), [options]);

  const updateOpts = (text?: string, value?: string | number) => {
    if (typeof options == "undefined") return;
    else if (typeof options == "function") {
      const opt = options(text, value ? [value] : []);
      if (isPromise(opt)) opt.then((r) => setOpts(r));
      // 是方法，但不是 Promise 方法的时候，直接设置
      else setOpts(opt as any);
    } else {
      if (text) {
        const opts = options.filter(
          (i) =>
            i.label.includes(text) ||
            String(i.value).includes(text) ||
            i.value == value
        );
        setOpts(opts);
      } else {
        setOpts(options);
      }
    }
  };

  // 如果 propsValue 是 null，表示选择了空，如果是 undefined 表示没选
  const value = isUndefined(propsValue) ? defaultValue : propsValue;

  return (
    <Select
      allowClear={meta?.allowClear}
      placeholder={placeholder}
      invalid={!isValid}
      search={search}
      disabled={disabled}
      value={value}
      options={opts}
      style={meta?.width ? { width: meta?.width } : undefined}
      onInputChange={updateOpts}
      onChange={onChange}
      notFoundContent={meta?.notFoundContent}
    />
  );
}
